package com.farm.web.restful;

import java.io.File;
import java.net.URLDecoder;
import java.util.Calendar;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.farm.authority.FarmAuthorityService;
import com.farm.authority.domain.Organization;
import com.farm.authority.domain.Outuser;
import com.farm.authority.domain.User;
import com.farm.authority.password.PasswordProviderService;
import com.farm.authority.service.OrganizationServiceInter;
import com.farm.authority.service.OutuserServiceInter;
import com.farm.authority.service.UserServiceInter;
import com.farm.core.auth.domain.LoginUser;
import com.farm.core.auth.exception.LoginUserNoAuditException;
import com.farm.core.auth.exception.LoginUserNoExistException;
import com.farm.core.page.ViewMode;
import com.farm.core.sql.query.DBRule;
import com.farm.core.sql.query.DBSort;
import com.farm.core.sql.query.DataQuery;
import com.farm.core.sql.result.DataResult;
import com.farm.parameter.FarmParameterService;
import com.farm.parameter.service.ParameterServiceInter;
import com.farm.sfile.WdapFileServiceInter;
import com.farm.sfile.domain.FileBase;
import com.farm.sfile.enums.FileModel;
import com.farm.sfile.exception.FileExNameException;
import com.farm.sfile.utils.FileCopyProcessCache;
import com.farm.util.web.IpComparaUtils;
import com.farm.web.WebUtils;
import com.farm.web.domain.Results;
import com.farm.web.filter.utils.LoginCertificateUtils;

/**
 * 组织机构、 [创建、查询、更新、删除] 用户、 [创建、查询、更新、删除] ---------------------------- 知识接口[查询]、
 * 分类接口[查询]、 问答接口[查询]、
 * 
 * @author wangdong
 *
 */
@RequestMapping("/api")
@Controller
public class ApiController extends WebUtils {
	private final static Logger log = Logger.getLogger(ApiController.class);
	@Resource
	private OrganizationServiceInter organizationServiceImpl;
	@Resource
	private UserServiceInter userServiceImpl;
	@Resource
	private OutuserServiceInter outUserServiceImpl;
	@Resource
	private WdapFileServiceInter wdapFileServiceImpl;
	@Resource
	private ParameterServiceInter parameterServiceImpl;

	/**
	 * 验证秘钥和用户信息
	 * 
	 * @param secret
	 */
	public static void checkAuth(String loginname, String plaintextPassword) {
		if (FarmParameterService.getInstance().getParameter("config.restful.debug").equals("true")) {
			return;
		}
		if (FarmParameterService.getInstance().getParameter("config.restful.secret.type").equals("complex")) {
			try {
				if (StringUtils.isBlank(loginname) || StringUtils.isBlank(plaintextPassword)) {
					throw new RuntimeException("loginname or password is null!");
				}
				if (!FarmAuthorityService.getInstance().isLegality(loginname,
						PasswordProviderService.getInstanceProvider().getClientPassword(plaintextPassword))) {
					throw new RuntimeException("user authentication is wrong! by verification error!");
				}
			} catch (LoginUserNoExistException e) {
				throw new RuntimeException("user authentication is wrong! by LoginUserNoExistException!");
			} catch (LoginUserNoAuditException e) {
				throw new RuntimeException("user authentication is wrong! by LoginUserNoAuditException!");
			}
		}
	}

	/**
	 * 验证秘钥
	 * 
	 * @param secret
	 */
	public static void checkSecret(String secret, HttpServletRequest request) {
		String ip = getCurrentIp(request);
		boolean whiteListAble = FarmParameterService.getInstance()
				.getParameterBoolean("config.restful.whitelist.state");
		if (whiteListAble) {
			String ips = FarmParameterService.getInstance().getParameter("config.restful.whitelist.ips");
			if (StringUtils.isNotBlank(ips)) {
				List<String> ipWhiteList = WebUtils.parseIds(ips.replaceAll("，", ","));
				if (StringUtils.isBlank(ip) || !(IpComparaUtils.isContainIp(ipWhiteList, ip))) {
					log.warn("WHITE-LIST:" + IpComparaUtils.getWhiteListTitle(ipWhiteList));
					throw new RuntimeException("the ip is not exist white list:" + ip);
				}
			} else {
				throw new RuntimeException("the ip white list is blank!");
			}
		}
		String state = FarmParameterService.getInstance().getParameter("config.restful.state");
		if (!state.toLowerCase().equals("true")) {
			throw new RuntimeException("the api is unable,check config file please!");
		}
		if (secret == null) {
			if (FarmParameterService.getInstance().getParameter("config.restful.debug").equals("true")) {
				return;
			} else {
				throw new RuntimeException("secret not exist!");
			}
		}
		if (!FarmParameterService.getInstance().getParameter("config.restful.secret.type").equals("none")) {
			log.info("have received remoteSecret:" + secret);
			// 从配置文件中读取秘钥
			String sysKey = FarmParameterService.getInstance().getParameter("config.restful.secret.key").trim();
			if (!secret.trim().equals(sysKey)) {
				if (!FarmParameterService.getInstance().getParameter("config.restful.debug").equals("true")) {
					throw new RuntimeException("secret error!");
				}
			}
		}
	}

	/**
	 * 获得当前用户
	 * 
	 * @return
	 */
	public static LoginUser getUser() {
		return new LoginUser() {
			@Override
			public String getName() {
				return "restful";
			}

			@Override
			public String getLoginname() {
				return "restful";
			}

			@Override
			public String getId() {
				return "restful";
			}

			@Override
			public String getType() {
				return "NONE";
			}

			@Override
			public String getIp() {
				return "NONE";
			}
		};
	}

	/**
	 * 获得当前用户
	 * 
	 * @return
	 */
	public static LoginUser getUser(String loginname) {
		if (StringUtils.isBlank(loginname)) {
			return getUser();
		}
		return FarmAuthorityService.getInstance().getUserByLoginName(loginname);
	}

	/**
	 * 查询所有组织机构
	 * 
	 * @param ID
	 * @param NAME
	 * @param PARENTID
	 * @param APPID
	 * @param session
	 * @return
	 */
	@RequestMapping("/get/organization")
	@ResponseBody
	public ResponseEntity<Map<String, Object>> getOrganization(String id, String name, String parentid, String appid,
			String secret, String operatorLoginname, String operatorPassword, HttpServletRequest request) {
		try {
			log.info("restful API:查询组织机构");
			checkSecret(secret, request);
			checkAuth(operatorLoginname, operatorPassword);
			DataQuery query = DataQuery.getInstance();
			// --------------------------------------------
			// ------------------------------------------
			if (StringUtils.isNotBlank(id)) {
				query.addRule(new DBRule("id", id, "="));
			}
			if (StringUtils.isNotBlank(name)) {
				query.addRule(new DBRule("name", name, "="));
			}
			if (StringUtils.isNotBlank(parentid)) {
				query.addRule(new DBRule("parentid", parentid, "="));
			}
			if (StringUtils.isNotBlank(appid)) {
				query.addRule(new DBRule("appid", appid, "="));
			}
			query.setPagesize(10000);
			// query.addRule(new DBRule("state", "1", "="));
			DataQuery dbQuery = DataQuery.init(query, "ALONE_AUTH_ORGANIZATION",
					"ID,TYPE,SORT,PARENTID,MUSER,CUSER,STATE,UTIME,CTIME,COMMENTS,NAME,TREECODE,APPID");
			DataResult result = dbQuery.search();
			// ------------------------------------------
			// ------------------------------------------
			Results resultObj = Results.getResults(result.getResultList(), result.getTotalSize(),
					result.getCurrentPage(), result.getPageSize());
			return ViewMode.getInstance().putAttr("DATA", resultObj).returnJsonMode();
		} catch (Exception e) {
			return ViewMode.getInstance().setError(e.getMessage(), e).returnJsonMode();
		}
	}

	/**
	 * 获得UTC时间
	 *
	 * @param session
	 * @return Map<String,Object>
	 */
	@RequestMapping(value = "/secret/utc")
	@ResponseBody
	public ResponseEntity<Map<String, Object>> utc(HttpSession session) {
		log.info("restful API:获得UTC时间，用于制作权限码");
		try {
			Calendar cal = Calendar.getInstance();
			return ViewMode.getInstance().putAttr("UTC", cal.getTimeInMillis()).returnJsonMode();
		} catch (Exception e) {
			return ViewMode.getInstance().setError(e.getMessage(), e).returnJsonMode();
		}
	}

	/**
	 * 创建组织机构
	 * 
	 * @param session
	 * @return Map<String,Object>
	 */
	@RequestMapping("/post/organization")
	@ResponseBody
	public ResponseEntity<Map<String, Object>> postOrganization(String parentid, String sort, String name,
			String comments, String secret, String appid, String operatorLoginname, String operatorPassword,
			HttpServletRequest request) {
		try {
			log.info("restful API:创建组织机构");
			checkSecret(secret, request);
			checkAuth(operatorLoginname, operatorPassword);
			Organization entity = new Organization();
			if (StringUtils.isNotBlank(parentid)) {
				entity.setParentid(parentid);
			}
			entity.setSort(Integer.valueOf(sort));
			entity.setName(name);
			entity.setComments(comments);
			entity.setType("1");
			entity.setAppid(appid);
			entity = organizationServiceImpl.insertOrganizationEntity(entity, getUser(operatorLoginname));
			return ViewMode.getInstance().putAttr("ID", entity.getId()).returnJsonMode();
		} catch (Exception e) {
			return ViewMode.getInstance().setError(e.getMessage(), e).returnJsonMode();
		}
	}

	/**
	 * 更新组织机构
	 * 
	 * @param session
	 * @return Map<String,Object>
	 */
	@RequestMapping("/put/organization")
	@ResponseBody
	public ResponseEntity<Map<String, Object>> putOrganization(String id, String sort, String name, String comments,
			String parentid, String secret, String operatorLoginname, String operatorPassword,
			HttpServletRequest request) {
		try {
			log.info("restful API:修改组织机构");
			checkSecret(secret, request);
			checkAuth(operatorLoginname, operatorPassword);
			Organization entity = organizationServiceImpl.getOrganizationEntity(id);
			if (StringUtils.isNotBlank(sort)) {
				entity.setSort(Integer.valueOf(sort));
			}
			if (StringUtils.isNotBlank(name)) {
				entity.setName(name);
			}
			if (StringUtils.isNotBlank(comments)) {
				entity.setComments(comments);
			}
			entity = organizationServiceImpl.editOrganizationEntity(entity, getUser(operatorLoginname));
			if (StringUtils.isNotBlank(parentid)) {
				organizationServiceImpl.moveOrgTreeNode(entity.getId(), parentid, getUser(operatorLoginname));
			}
			return ViewMode.getInstance().returnJsonMode();
		} catch (Exception e) {
			return ViewMode.getInstance().setError(e.getMessage(), e).returnJsonMode();
		}
	}

	/**
	 * 删除组织机构
	 * 
	 * @param session
	 * @return Map<String,Object>
	 */
	@RequestMapping("/delete/organization")
	@ResponseBody
	public ResponseEntity<Map<String, Object>> delOrganization(String id, String secret, String operatorLoginname,
			String operatorPassword, HttpServletRequest request) {
		try {
			log.info("restful API:删除组织机构");
			checkSecret(secret, request);
			checkAuth(operatorLoginname, operatorPassword);
			organizationServiceImpl.deleteOrganizationEntity(id, getUser(operatorLoginname));
			return ViewMode.getInstance().returnJsonMode();
		} catch (Exception e) {
			return ViewMode.getInstance().setError(e.getMessage(), e).returnJsonMode();
		}
	}

	/**
	 * 查询所有用户
	 * 
	 * @param ID
	 * @param NAME
	 * @param PARENTID
	 * @param APPID
	 * @param session
	 * @return
	 */
	@RequestMapping("/get/outer")
	@ResponseBody
	public ResponseEntity<Map<String, Object>> getUser(String accountid, String secret, String operatorLoginname,
			String operatorPassword, HttpServletRequest request) {
		try {
			log.info("restful API:查询用户");
			checkSecret(secret, request);
			checkAuth(operatorLoginname, operatorPassword);
			Outuser outer = outUserServiceImpl.getOutuserByAccountId(accountid);
			if (outer == null) {
				throw new RuntimeException("账户为" + accountid + "的外部用户无法找到！");
			}
			User user = userServiceImpl.getUserEntity(outer.getUserid());
			if (user == null) {
				throw new RuntimeException("ID为" + outer.getUserid() + "的用户无法找到！");
			}
			ViewMode view = ViewMode.getInstance();
			view.putAttr("USERID", user.getId());
			view.putAttr("USERNAME", user.getName());
			view.putAttr("USERSTATE", user.getState());
			view.putAttr("USERTYPE", user.getType());
			view.putAttr("LOGINNAME", user.getLoginname());
			view.putAttr("OUTERNAME", outer.getAccountname());
			view.putAttr("OUTERSTATE", outer.getPstate());
			return view.returnJsonMode();
		} catch (Exception e) {
			return ViewMode.getInstance().setError(e.getMessage(), e).returnJsonMode();
		}
	}

	/**
	 * 查询所有用户
	 * 
	 * @param ID
	 * @param NAME
	 * @param PARENTID
	 * @param APPID
	 * @param session
	 * @return
	 */
	@RequestMapping("/get/user")
	@ResponseBody
	public ResponseEntity<Map<String, Object>> getUser(String id, String loginname, String type, String state,
			String orgid, String secret, String operatorLoginname, String operatorPassword,
			HttpServletRequest request) {
		try {
			log.info("restful API:查询用户");
			checkSecret(secret, request);
			checkAuth(operatorLoginname, operatorPassword);
			DataQuery query = DataQuery.getInstance();
			// --------------------------------------------
			// ------------------------------------------
			if (StringUtils.isNotBlank(id)) {
				query.addRule(new DBRule("USER.ID", id, "="));
			}
			if (StringUtils.isNotBlank(loginname)) {
				query.addRule(new DBRule("USER.LOGINNAME", loginname, "="));
			}
			if (StringUtils.isNotBlank(type)) {
				query.addRule(new DBRule("USER.TYPE", type, "="));
			}
			if (StringUtils.isNotBlank(state)) {
				query.addRule(new DBRule("USER.STATE", state, "="));
			}
			if (StringUtils.isNotBlank(orgid)) {
				query.addRule(new DBRule("RFORG.ORGANIZATIONID", orgid, "="));
			}
			query.setPagesize(10000);
			DataQuery dbQuery = DataQuery.init(query,
					"ALONE_AUTH_USER USER left join ALONE_AUTH_USERORG RFORG on USER.ID=RFORG.USERID",
					"USER.ID as ID,USER.NAME as NAME,RFORG.ORGANIZATIONID as ORGANIZATIONID,USER.COMMENTS as COMMENTS,USER.TYPE as TYPE,USER.LOGINNAME as LOGINNAME,USER.IMGID as IMGID,USER.STATE as STATE");
			DataResult result = dbQuery.search();
			// ------------------------------------------
			// ------------------------------------------
			Results resultObj = Results.getResults(result.getResultList(), result.getTotalSize(),
					result.getCurrentPage(), result.getPageSize());
			return ViewMode.getInstance().putAttr("DATA", resultObj).returnJsonMode();
		} catch (Exception e) {
			return ViewMode.getInstance().setError(e.getMessage(), e).returnJsonMode();
		}
	}

	/**
	 * 创建用户
	 * 
	 * @param session
	 * @return Map<String,Object>
	 */
	@RequestMapping("/post/user")
	@ResponseBody
	public ResponseEntity<Map<String, Object>> postUser(String name, String loginname, String state, String type,
			String comments, String orgid, String secret, String operatorLoginname, String operatorPassword,
			HttpServletRequest request) {
		try {
			log.info("restful API:创建用户");
			checkSecret(secret, request);
			checkAuth(operatorLoginname, operatorPassword);
			User entity = new User();
			entity.setLoginname(loginname);
			entity.setName(name);
			if (StringUtils.isNotBlank(comments)) {
				entity.setComments(comments);
			}
			if (StringUtils.isNotBlank(type)) {
				entity.setType(type);
			} else {
				entity.setType("1");
			}
			if (StringUtils.isNotBlank(state)) {
				entity.setState(state);
			} else {
				entity.setState("1");
			}
			entity = userServiceImpl.insertUserEntity(entity, getUser(operatorLoginname));
			if (StringUtils.isNotBlank(orgid)) {
				userServiceImpl.setUserOrganization(entity.getId(), orgid, getUser());
			}
			return ViewMode.getInstance().putAttr("ID", entity.getId()).returnJsonMode();
		} catch (Exception e) {
			return ViewMode.getInstance().setError(e.getMessage(), e).returnJsonMode();
		}
	}

	/**
	 * 更新用户
	 * 
	 * @param session
	 * @return Map<String,Object>
	 */
	@RequestMapping("/put/user")
	@ResponseBody
	public ResponseEntity<Map<String, Object>> putUser(String id, String name, String loginname, String state,
			String comments, String orgid, String type, String secret, String operatorLoginname,
			String operatorPassword, HttpServletRequest request) {
		try {
			log.info("restful API:修改用户");
			checkSecret(secret, request);
			checkAuth(operatorLoginname, operatorPassword);
			User entity = userServiceImpl.getUserEntity(id);
			if (StringUtils.isNotBlank(name)) {
				entity.setName(name);
			}
			if (StringUtils.isNotBlank(loginname)) {
				entity.setLoginname(loginname);
			}
			if (StringUtils.isNotBlank(comments)) {
				entity.setComments(comments);
			}
			if (StringUtils.isNotBlank(type)) {
				entity.setType(type);
			}
			if (StringUtils.isNotBlank(state)) {
				entity.setState(state.equals("0") ? "0" : "1");
			}
			entity = userServiceImpl.editUserEntity(entity, getUser(operatorLoginname));
			if (StringUtils.isNotBlank(orgid)) {
				userServiceImpl.setUserOrganization(id, orgid, getUser(operatorLoginname));
			}
			return ViewMode.getInstance().returnJsonMode();
		} catch (Exception e) {
			return ViewMode.getInstance().setError(e.getMessage(), e).returnJsonMode();
		}
	}

	/**
	 * 删除用户
	 * 
	 * @param session
	 * @return Map<String,Object>
	 */
	@RequestMapping("/delete/user")
	@ResponseBody
	public ResponseEntity<Map<String, Object>> delUser(String id, String secret, String operatorLoginname,
			String operatorPassword, HttpServletRequest request) {
		try {
			log.info("restful API:删除用户");
			checkSecret(secret, request);
			checkAuth(operatorLoginname, operatorPassword);
			userServiceImpl.deleteUserEntity(id, getUser(operatorLoginname));
			return ViewMode.getInstance().returnJsonMode();
		} catch (Exception e) {
			return ViewMode.getInstance().setError(e.getMessage(), e).returnJsonMode();
		}
	}

	/**
	 * 用户登录注册,返回后的验证码可以用来在前台登录
	 * 
	 * @param loginname
	 * @param secret
	 * @param session
	 * @return
	 */
	@RequestMapping("/regist/login")
	@ResponseBody
	public ResponseEntity<Map<String, Object>> registLogin(String loginname, String secret, String operatorLoginname,
			String operatorPassword, HttpServletRequest request) {
		try {
			log.info("restful API:查询用户");
			checkSecret(secret, request);
			checkAuth(operatorLoginname, operatorPassword);
			// ------------------------------------------
			// 判断登录名是否存在
			if (userServiceImpl.getUserByLoginName(loginname) == null) {
				throw new RuntimeException("loginname is not exist!");
			}
			// 通过用登录名注册到
			String uuid = LoginCertificateUtils.registLoginCertificate(loginname);
			// ------------------------------------------
			return ViewMode.getInstance().putAttr("CERTIFICATE", uuid).returnJsonMode();
		} catch (Exception e) {
			return ViewMode.getInstance().setError(e.getMessage(), e).returnJsonMode();
		}
	}

	/**
	 * 授權远程用户登陆或注册
	 * 
	 * @param loginname
	 * @param secret
	 * @param session
	 * @return
	 */
	@RequestMapping("/regist/oulogin")
	@ResponseBody
	public ResponseEntity<Map<String, Object>> regisOulogin(String accountid, String accountname, String secret,
			String operatorLoginname, String operatorPassword, HttpServletRequest request) {
		try {
			log.info("restful API:查询用户");
			checkSecret(secret, request);
			checkAuth(operatorLoginname, operatorPassword);
			// ------------------------------------------
			if (StringUtils.isBlank(accountid) || StringUtils.isBlank(accountname)) {
				throw new RuntimeException("参数错误!");
			}
			// 判断登录名是否存在
			LoginUser loginuser = outUserServiceImpl.getLocalUserByAccountId(accountid);
			if (loginuser != null) {
				// 通过用登录名注册到
				String uuid = LoginCertificateUtils.registLoginCertificate(loginuser.getLoginname());
				// ------------------------------------------
				return ViewMode.getInstance().putAttr("ISLOCAL", true).putAttr("LOGINNAME", loginuser.getLoginname())
						.putAttr("CERTIFICATE", uuid).returnJsonMode();
			} else {
				Outuser outuser = outUserServiceImpl.creatOutUser(accountid, accountname, "CAS");
				String uuid = LoginCertificateUtils.registLoginCertificate(outuser.getId());
				return ViewMode.getInstance().putAttr("ISLOCAL", false).putAttr("OUTUSERID", outuser.getId())
						.putAttr("CERTIFICATE", uuid).returnJsonMode();
			}
		} catch (Exception e) {
			return ViewMode.getInstance().setError(e.getMessage(), e).returnJsonMode();
		}
	}

	/**
	 * 通过用户登录注册的验证码,查找用户的登录名
	 * 
	 * @param loginname
	 * @param secret
	 * @param session
	 * @return
	 */
	@RequestMapping("/get/login")
	@ResponseBody
	public ResponseEntity<Map<String, Object>> getLogin(String certificate, String secret, HttpServletRequest request) {
		try {
			log.info("restful API:查询用户");
			checkSecret(secret, request);
			// ------------------------------------------
			String loginname = LoginCertificateUtils.getLoginNameByCertificate(certificate);
			// ------------------------------------------
			return ViewMode.getInstance().putAttr("LOGINNAME", loginname).returnJsonMode();
		} catch (Exception e) {
			return ViewMode.getInstance().setError(e.getMessage(), e).returnJsonMode();
		}
	}

	/**
	 * 上传base64位图片
	 * 
	 * @param session
	 * @return Map<String,Object>
	 */
	@RequestMapping("/add/base64img")
	@ResponseBody
	public ResponseEntity<Map<String, Object>> upimg(String base64, String filename, String secret,
			String operatorLoginname, String operatorPassword, HttpServletRequest request) {
		String fileid = null;
		String imgurl = null;
		try {
			log.info("restful API:上传base64图片");
			checkSecret(secret, request);
			checkAuth(operatorLoginname, operatorPassword);
			byte[] data = Base64.decodeBase64(base64);
			String exname = filename.substring(filename.lastIndexOf(".") + 1);
			String maxLength = FarmParameterService.getInstance().getParameter("config.doc.upload.length.max");
			if (data.length > Long.valueOf(maxLength)) {
				throw new Exception("文件不能超过" + Long.valueOf(maxLength) / 1024 + "kb");
			}
			// 验证类型
			if (!FileModel.getModelByFileExName(exname).equals(FileModel.IMG)) {
				throw new Exception("文件类型错误，允许的类型为：图片");
			}
			wdapFileServiceImpl.saveLocalFile(data, FileModel.IMG, filename, getUser(operatorLoginname));
			imgurl = wdapFileServiceImpl.getDownloadUrl(fileid, FileModel.IMG);
		} catch (Exception e) {
			return ViewMode.getInstance().setError(e.getMessage(), e).returnJsonMode();
		}
		return ViewMode.getInstance().putAttr("FILEID", fileid).putAttr("URL", imgurl).returnJsonMode();
	}

	/**
	 * 上传一个本地文件
	 * 
	 * @param filePath
	 * @param secret
	 * @param session
	 * @return
	 */
	@RequestMapping("/add/localFile")
	@ResponseBody
	public ResponseEntity<Map<String, Object>> localFile(String filePath, String secret, String operatorLoginname,
			String operatorPassword, HttpServletRequest request) {
		String fileid = null;
		String url = null;
		try {
			log.info("restful API:上传本地文件");
			checkSecret(secret, request);
			checkAuth(operatorLoginname, operatorPassword);
			String maxLength = FarmParameterService.getInstance().getParameter("config.doc.upload.length.max");
			File file = new File(filePath);
			if (file.length() > Long.valueOf(maxLength)) {
				throw new Exception("文件不能超过" + Long.valueOf(maxLength) / 1024 + "kb");
			}
			// 验证类型
			String exname = file.getName().substring(file.getName().lastIndexOf(".") + 1);
			FileBase fbase = wdapFileServiceImpl.saveLocalFile(file, FileModel.getModelByFileExName(exname),
					getUser(operatorLoginname), null);
			fileid = fbase.getId();
			url = wdapFileServiceImpl.getDownloadUrl(fileid, FileModel.getModelByFileExName(exname));
		} catch (Exception e) {
			return ViewMode.getInstance().setError(e.getMessage(), e).returnJsonMode();
		}
		return ViewMode.getInstance().putAttr("FILEID", fileid).putAttr("URL", url).returnJsonMode();
	}

	/**
	 * 上传附件文件
	 * 
	 * @param file
	 *            附件对象
	 * @param filename
	 *            文件名称
	 * @param processkey
	 *            进度查询key，可根据该key获得远程处理进度
	 * @param syncid
	 *            同步ID，根据该id判断是否重复上传文件（如果数据已有该key的话）
	 * @param secret
	 * @param operatorLoginname
	 * @param operatorPassword
	 * @param request
	 * @return
	 */
	@RequestMapping("/add/upfile")
	@ResponseBody
	public ResponseEntity<Map<String, Object>> upload(@RequestParam(value = "file", required = true) MultipartFile file,
			String filename, String processkey, String syncid, String secret, String operatorLoginname,
			String operatorPassword, HttpServletRequest request) {
		ViewMode page = ViewMode.getInstance();
		try {
			log.info("restful API:上传远程文件");
			FileBase bfile = null;
			if (StringUtils.isNotBlank(syncid)) {
				// 如果该附件已经上传过
				String fileid = wdapFileServiceImpl.getFileIdByAppId(syncid);
				if (StringUtils.isNotBlank(fileid)) {
					bfile = wdapFileServiceImpl.getFileBase(fileid);
				}
			}
			if (bfile == null) {
				checkSecret(secret, request);
				checkAuth(operatorLoginname, operatorPassword);
				if (StringUtils.isBlank(operatorLoginname)) {
					throw new RuntimeException("operatorLoginname 为必填项,不可省略");
				}
				filename = URLDecoder.decode(filename, "utf-8");
				try {
					filename = filename.replaceAll("\\+", "%20");
				} catch (Exception e) {
					e.printStackTrace();
				}
				String exname = filename.substring(filename.lastIndexOf(".") + 1);
				LoginUser opuser = FarmAuthorityService.getInstance().getUserByLoginName(operatorLoginname);
				String filekey = opuser.getId() + processkey;
				bfile = wdapFileServiceImpl.saveLocalFile(file, FileModel.getModelByFileExName(exname), opuser,
						filekey);
				wdapFileServiceImpl.updateFileAppid(bfile.getId(), syncid, opuser);
				page.putAttr("ISREPEAT", false);
			} else {
				page.putAttr("ISREPEAT", true);
				log.info("附件已经存在，直接返回!");
			}
			return getFormatFileInfo(page, bfile);
		} catch (Exception e) {
			return ViewMode.getInstance().setError(e.getMessage(), e).returnJsonMode();
		}
	}

	private ResponseEntity<Map<String, Object>> getFormatFileInfo(ViewMode page, FileBase bfile)
			throws FileExNameException {
		return page
				.putAttr("URL",
						wdapFileServiceImpl.getDownloadUrl(bfile.getId(),
								FileModel.getModelByFileExName(bfile.getExname())))
				.putAttr("FILEID", bfile.getId()).putAttr("FILENAME", bfile.getTitle())
				.putAttr("SAFECODE", bfile.getSecret()).returnJsonMode();

	}

	/**
	 * 获得附件上传服务器端处理进度
	 * 
	 * @param processkey
	 * @param secret
	 * @param operatorLoginname
	 * @param operatorPassword
	 * @param request
	 * @return
	 */
	@RequestMapping("/add/upprocess")
	@ResponseBody
	public ResponseEntity<Map<String, Object>> PubUploadProcess(String processkey, String secret,
			String operatorLoginname, String operatorPassword, HttpServletRequest request) {
		ViewMode view = ViewMode.getInstance();
		Integer process = 0;
		try {
			log.info("restful API:上传base64图片");
			checkSecret(secret, request);
			checkAuth(operatorLoginname, operatorPassword);
			LoginUser opuser = FarmAuthorityService.getInstance().getUserByLoginName(operatorLoginname);
			String filekey = opuser.getId() + processkey;
			process = FileCopyProcessCache.getProcess(filekey);
			return view.putAttr("PROCESS", process).returnJsonMode();
		} catch (Exception e) {
			return ViewMode.getInstance().setError(e.getMessage(), e).returnJsonMode();
		}
	}

	/**
	 * 通過同步id獲得遠程文件信息
	 * 
	 * @param processkey
	 * @param secret
	 * @param operatorLoginname
	 * @param operatorPassword
	 * @param request
	 * @return
	 */
	@RequestMapping("/find/syncfile")
	@ResponseBody
	public ResponseEntity<Map<String, Object>> PubSyncfile(String syncid, String secret, String operatorLoginname,
			String operatorPassword, HttpServletRequest request) {
		ViewMode page = ViewMode.getInstance();
		try {
			log.info("restful API:获得已同步文件");
			checkSecret(secret, request);
			checkAuth(operatorLoginname, operatorPassword);
			String fileid = wdapFileServiceImpl.getFileIdByAppId(syncid);
			if (fileid == null) {
				return page.putAttr("ISREPEAT", false).returnJsonMode();
			} else {
				FileBase bfile = wdapFileServiceImpl.getFileBase(fileid);
				return getFormatFileInfo(page.putAttr("ISREPEAT", true), bfile);
			}
		} catch (Exception e) {
			return ViewMode.getInstance().setError(e.getMessage(), e).returnJsonMode();
		}
	}

	/**
	 * 查询系統參數
	 * 
	 * @param ID
	 * @param NAME
	 * @param PARENTID
	 * @param APPID
	 * @param session
	 * @return
	 */
	@RequestMapping("/get/parameter")
	@ResponseBody
	public ResponseEntity<Map<String, Object>> getParameter(String key, String secret, String operatorLoginname,
			String operatorPassword, HttpServletRequest request) {
		try {
			log.info("restful API:查询系統參數");
			checkSecret(secret, request);
			checkAuth(operatorLoginname, operatorPassword);
			String val = FarmParameterService.getInstance().getParameter(key);
			return ViewMode.getInstance().putAttr("DATA", val).returnJsonMode();
		} catch (Exception e) {
			return ViewMode.getInstance().setError(e.getMessage(), e).returnJsonMode();
		}
	}

	/**
	 * 设置系統參數
	 * 
	 * @param ID
	 * @param NAME
	 * @param PARENTID
	 * @param APPID
	 * @param session
	 * @return
	 */
	@RequestMapping("/put/parameter")
	@ResponseBody
	public ResponseEntity<Map<String, Object>> putParameter(String key, String val, String secret,
			String operatorLoginname, String operatorPassword, HttpServletRequest request) {
		try {
			log.info("restful API:查询系統參數");
			checkSecret(secret, request);
			checkAuth(operatorLoginname, operatorPassword);
			parameterServiceImpl.setValue(key, val, getUser(operatorLoginname));
			parameterServiceImpl.refreshCache();
			return ViewMode.getInstance().returnJsonMode();
		} catch (Exception e) {
			return ViewMode.getInstance().setError(e.getMessage(), e).returnJsonMode();
		}
	}
}
